import 'dart:async';
import 'package:flutter/material.dart';
import 'package:qgchat/common/class/overlay/index.dart';
import 'package:qgchat/common/global/global.dart';

// 通知广播
class GlobalNotice {
  // 单例
  static final GlobalNotice _instance = GlobalNotice._internal();
  factory GlobalNotice() => _instance;
  GlobalNotice._internal() {
    state.addListener(() {
      if (!state.value) {
        clearWidget();
        _show();
      }
    });
  }

  // 通知组件
  OverlayEntry _overlayEntry;

  // 通知控制器
  ValueNotifier state = ValueNotifier<bool>(false);

  // 通知列表
  List<NoticeModel> _list = [];

  // 加入队列
  push(NoticeModel info) async {
    _list.add(info);
    if (!state.value) {
      _show();
    }
  }

  // 启动显示
  _show() async {
    if (_list.length > 0) {
      final info = _list[0];
      _overlayEntry = OverlayEntry(
        builder: (context) => NoticeBuilder(
          ctrl: state,
          info: info,
        ),
      );
      appOverlayState.insert(_overlayEntry);
      state.value = true;
      _list.removeAt(0);
    }
  }

  // 清除当前的组件
  clearWidget() {
    _overlayEntry?.remove();
    _overlayEntry = null;
  }

  // 销毁
  dispose() {
    clearWidget();
    state.dispose();
  }
}

// 通知消息的模型
class NoticeModel {
  String name;
  int gold;

  NoticeModel({this.name, this.gold});

  NoticeModel.fromJson(Map<String, dynamic> json) {
    name = json['name'];
    gold = json['gold'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['name'] = this.name;
    data['gold'] = this.gold;
    return data;
  }
}

// 通知的组件
class NoticeBuilder extends StatefulWidget {
  final ValueNotifier<bool> ctrl;
  final NoticeModel info;

  NoticeBuilder({
    @required this.ctrl,
    @required this.info,
    Key key,
  }) : super(key: key);

  @override
  _NoticeBuilderState createState() => _NoticeBuilderState();
}

class _NoticeBuilderState extends State<NoticeBuilder> {
  Duration animatedTime = Duration(seconds: 15);
  bool _end = false;

  @override
  void initState() {
    super.initState();
    if (!mounted) return;

    Timer(
      Duration(seconds: 1),
      () {
        setState(() {
          _end = true;
        });
      },
    );

    Timer(
      animatedTime,
      () {
        widget.ctrl.value = false;
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    final statusTop = MediaQuery.of(context).padding.top;
    final width = MediaQuery.of(context).size.width;

    return Stack(
      children: [
        AnimatedPositioned(
          top: statusTop + 56 - px(28),
          left: _end ? -width : width,
          duration: animatedTime,
          child: Container(
            height: px(56),
            padding: EdgeInsets.only(
              left: px(24),
              right: px(24),
            ),
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(px(28)),
              gradient: LinearGradient(
                colors: [col('cd86ff'), col('5636d8')],
              ),
            ),
            child: Stack(
              overflow: Overflow.visible,
              children: [
                Row(
                  children: [
                    Container(
                      width: px(32),
                      height: px(25),
                      margin: EdgeInsets.only(right: px(10)),
                      child: Image.asset("assets/images/icon/laba.png"),
                    ),
                    Align(
                      alignment: Alignment.center,
                      child: RichText(
                        text: TextSpan(
                          children: [
                            TextSpan(
                              text: "${widget.info.name}",
                              style: TextStyle(
                                color: col('fee34a'),
                                fontSize: px(26),
                              ),
                            ),
                            TextSpan(text: " "),
                            TextSpan(
                              text: "充值了${widget.info.gold}金币",
                              style: TextStyle(
                                color: col('ffffff'),
                                fontSize: px(26),
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                  ],
                ),
                Positioned(
                  top: 0,
                  right: px(-44),
                  child: Container(
                    width: px(41),
                    height: px(33),
                    child: Image.asset("assets/images/icon/laba2.png"),
                  ),
                ),
              ],
            ),
          ),
        )
      ],
    );
  }
}
